package graph;

import java.util.Arrays;

/**
 * 领接矩阵
 */
public class GraphByMatrix {
    public char[] arrayV;// 定点数组
    public int[][] matrix;// 矩阵
    public boolean isDirect;// true 是有向图 false 是无向图
    public GraphByMatrix(int size,boolean isDirect) {
        this.arrayV = new char[size];
        this.matrix = new int[size][size];
        for(int i = 0;i < size;i++) {
            Arrays.fill(matrix[i],Constant.MAX);
        }
        this.isDirect = isDirect;
    }
    public void initArrayV(char[] array) {
        for(int i = 0; i < array.length;i++) {
            arrayV[i] = array[i];
        }
    }
    public void addEdge(char srcV,char destV,int weight) {
        int src = getIndexOfV(srcV);
        for(int i = 0; i < arrayV.length;i++) {
            if(arrayV[i] == destV) {
                matrix[src][i] = weight;
            }
        }
        if(!isDirect) {
            // 代表是无向图，两条边都需要插入
            int dest = getIndexOfV(destV);
            for(int i = 0; i < arrayV.length;i++) {
                if(matrix[dest][i] == srcV) {
                    matrix[dest][i] = weight;
                }
            }
        }
    }

    private int getIndexOfV(char srcV) {
        for(int i = 0; i < arrayV.length;i++) {
            if(arrayV[i] == srcV) {
                return i;
            }
        }
        return -1;
    }

    public void printGraph() {
        System.out.print("   ");
        for(int i = 0; i < arrayV.length;i++) {
            System.out.print(arrayV[i] + "  ");
        }
        System.out.println();
        for(int i = 0; i < arrayV.length;i++) {
            System.out.print(arrayV[i] + " ");
            for(int j = 0; j < arrayV.length;j++) {
                if(matrix[i][j] != Constant.MAX) {
                    System.out.print( " "+matrix[i][j] + " ");
                }else {
                    System.out.print(" * ");
                }
            }
            System.out.println();
        }
    }
    // 获取度
    public int getDevOfV(char srcV) {
        int src = getIndexOfV(srcV);
        int count = 0;
        for(int i = 0; i < arrayV.length;i++) {
            if(matrix[src][i] != Constant.MAX) {
                count++;
            }
        }
        if(!isDirect) {
            for(int i = 0; i < arrayV.length;i++) {
                if(matrix[i][src] != Constant.MAX) {
                    count++;
                }
            }
        }
        return count;
    }
}
